package com.FrameWork.Synchoronization;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIP
{
	public static String uncompress(String str) throws IOException
	{
		return uncompress(str.getBytes("utf-8"));
	}

	// 解压缩
	public static String uncompress(byte[] bytes) throws IOException
	{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		GZIPInputStream gunzip = new GZIPInputStream(in);
		byte[] buffer = new byte[256];
		int n;
		while ((n = gunzip.read(buffer)) >= 0)
		{
			out.write(buffer, 0, n);
		}
		// toString()使用平台默认编码，也可以显式的指定如toString("GBK")
		return out.toString();
	}

	// 解压缩
	public static String uncompress(InputStream in) throws IOException
	{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPInputStream gunzip = new GZIPInputStream(in);
		byte[] buffer = new byte[256];
		int n;
		while ((n = gunzip.read(buffer)) >= 0)
		{
			out.write(buffer, 0, n);
		}
		// toString()使用平台默认编码，也可以显式的指定如toString("GBK")
		return out.toString();
	}



	public static byte[]
			compress(String str) throws UnsupportedEncodingException
			{
		return compress(str.getBytes("utf-8"));
			}

	/**
	 * gZip压缩方法
	 * */
	public static byte[] compress(byte[] data)
	{
		byte[] b = null;
		try
		{
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			GZIPOutputStream gzip = new GZIPOutputStream(bos);
			gzip.write(data);
			gzip.finish();
			gzip.close();
			
			b = bos.toByteArray();
			bos.flush();
			bos.close();
			bos = null;
			System.gc();
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return b;
	}
}
